package com.neuedu.yyzx.interceptor;

import com.neuedu.yyzx.common.Ret;
import com.neuedu.yyzx.config.security.SecurityUtils;
import com.neuedu.yyzx.utils.JSONWriteUtils;
import com.neuedu.yyzx.utils.JWTUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * @author 金山
 * 项目：yyzx
 * site: https://blog.fulfill.com.cn
 * 描述
 * @data 2025/3/2811:32
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {


    @Autowired
    SecurityUtils securityUtils;


    // 用于判断是否 允许放行
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        /*
         *      获取token
         *      2.1  有token  放行
         *      2.2  没有token  组织
         */


        String token = request.getHeader("Authorization");
        if (token == null || token.trim().length() == 0) {   // 401
            // System.out.println("异常的情况 ");
            JSONWriteUtils.write(response, Ret.unauthorized());
            return false;
        }

        boolean tokenVerify = JWTUtils.verify(token);
        if (!tokenVerify) {
            // System.out.println("无效的Token ");  // 403
            JSONWriteUtils.write(response, Ret.forbidden());
            return false;
        }

        Object userInfo = securityUtils.getUserInfo();
        System.out.println("用户身份: userInfo = " + userInfo);

        // System.out.println("正常的token");


        return true;
    }


}
